2099. Find Subsequence of Length K With the Largest Sum - LeetCode Solution


Sorting greedy

Python Code:

class Solution:
    def maxSubsequence(self, num: List[int], k: int) -> List[int]:
        nums = sorted(num)
        dict1 = {}
        for i in range(len(nums)-1, -1, -1):
            if k==0:
                break
            if nums[i] in dict1:
                dict1[nums[i]] +=1
            else:
                dict1[nums[i]]= 1
            k-=1
        ans = []
        
        for i in num:
            if i in dict1:
                if dict1[i] !=0:
                    ans.append(i)
                    dict1[i] -=1
        return ans


Comments

Submit
0 Comments
More Questions

938A - Word Correction
159C - String Manipulation 10
258A - Little Elephant and Bits
1536C - Diluc and Kaeya
1428C - ABBB
1557A - Ezzat and Two Subsequences
255A - Greg's Workout
1059A - Cashier
1389C - Good String
1561A - Simply Strange Sort
1337B - Kana and Dragon Quest game
137C - History
1443C - The Delivery Dilemma
6C - Alice Bob and Chocolate
1077C - Good Array
285B - Find Marble
6A - Triangle
1729A - Two Elevators
1729B - Decode String
1729C - Jumping on Tiles
1729E - Guess the Cycle Size
553B - Kyoya and Permutation
1729D - Friends and the Restaurant
1606C - Banknotes
580C - Kefa and Park
342A - Xenia and Divisors
1033A - King Escape
39D - Cubical Planet
1453A - Cancel the Trains
645A - Amity Assessment